package com.szalay.desktopsearch.ui;

import com.szalay.desktopsearch.search.Search;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import org.apache.solr.client.solrj.SolrServerException;

/**
 * Search panel.
 * @author szalay
 */
public class SearchPanel extends JPanel {
    private static final long serialVersionUID = 1720803655426222890L;
    
    /** Creates a new search window. */
    public SearchPanel(final Search search) {
        final BorderLayout layout = new BorderLayout();
        setLayout(layout);
        
        //Status bar
        final StatusBar statusBar = new StatusBar();
         
        //add a text field
        final JTextField textField = new JTextField();
        textField.getDocument().addDocumentListener(new DocumentListener() {
            private void search() {
                if (textField.getText() == null) {
                    return;
                }

                if (textField.getText().length() < 3) {
                    return;
                }
                try {
                    search.search(textField.getText(), 0, 10);
                } catch (SolrServerException ex) {
                    statusBar.setText("Error: " + ex.toString());
                }
            }

            @Override
            public void insertUpdate(DocumentEvent e) {
                search();
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                search();
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                 search();
            }
        });
        
        final SearchResultTable table = new SearchResultTable(800);
        search.addSearchListener(table);
        search.addSearchListener(statusBar);
        
        final Scroller scroller = new Scroller(search);
        search.addSearchListener(scroller);
           
        //The top panel contains the search text field and the scroller
        final JPanel topPanel = new JPanel();
        final GridLayout topPanelLayout = new GridLayout(2, 1);
        topPanel.setLayout(topPanelLayout);
        topPanel.add(textField);
        topPanel.add(scroller);
        
        add(topPanel, BorderLayout.NORTH);
        add(table, BorderLayout.CENTER);
        add(statusBar, BorderLayout.SOUTH);
        
        textField.requestFocus();
    }
}
    
